sumFactors = 0;
$(document).ready(function(){
    changeTotalPrice();
    totalTime();
    addPackage();
    deletePackage();
    beforehSubmit();
    changePointOrigin();
    $('#pointSeller').trigger('change');
})

function deletePackage()
{
    var id = $('#idClient').val();
    $('.deletePackage').live('click',function()
    {
        var idPackage = $(this).attr('id');
        if(confirm('Estas seguro que deseas eliminar este paquete?'))
        {
            $.post(urlDeletePackage, {
                'id':id,
                'idPackage':idPackage
            },function(data){
                $('#tablePackage').html(data);
                changeUnitarys();
            }); 
        }
    })
}

function addPackage()
{ 
    var id = $('#idClient').val();
    $('#addPackage').live('click',function()
    {
        $('#divAdd').dialog('open');
        $.post(urlConsultPackage,{
            'id': id
        },function(data){
            $('#divAdd').html(data);
        })
    });
    
        
    $('#divAdd').dialog({
        autoOpen: false,
        modal:true,
        resizable:false,
        buttons: {
            Aceptar:
            {
                text:'Accept',
                click: function()
                {
                    peso = $('#peso').val();
                    alto = $('#alto').val();
                    ancho = $('#ancho').val();
                    profundidad = $('#profundidad').val();
                    nombre = $('#nombre').val();
                    $.post(urlSavePackage,{
                        'id':id,
                        'peso':peso,
                        'alto':alto,
                        'ancho':ancho,
                        'profundidad':profundidad,
                        'nombre':nombre
                    },
                    function(data){
                        $('#tablePackage').html(data);
                        $('#divAdd').dialog('close');
                        changeUnitarys();
                    })
                }                    
            }
        },
        closeText: 'hide',
        width:450
    });
     
    
}

function totalTime()
{
    $('#boxSchedules, #pointBuyer').change(function(){
        var idRoute = $('#boxSchedules').val();
        pointOrigin = $('#pointSeller').val();
        pointDestiny  = $('#pointBuyer').val();
        if(idRoute > 0)
        {
            $.post(urlCalculateShippingTime, {
                idRoute : idRoute,
                buyerId : buyerId,
                orderId : orderId,
                pointSeller:pointOrigin,
                pointBuyer :pointDestiny 
            }, function(data){
                if(data.res)
                {
                    $('#shippingDate').val(data.date);
                }
                else
                {
                    $('#shippingDate').val('');
                }
                $('#shippingDateInformation').html('<div class="alert">'+data.message+'</div>');
                /* Se suma el factor de las rutas*/
                sumFactors = 0;
                $.each(data.factors, function(key, value) { 
                  sumFactors += value.factor; 
                });
                changeUnitarys();
            },'json');
        }
        else
            $('#shippingDateInformation').html('<div class="alert">Seleccione la fecha de recolecci&oacute;n</div>');    
    });
}

function changeTotalPrice(){

    $('.boxunity').live('change',function(){
        var unidades = $(this).val();
        var price = $(this).attr('price');
        var id = $(this).attr('pid');
        var width = $('#width_'+id).val();
        var height = $('#height_'+id).val();
        var depth = $('#depth_'+id).val();
        var vol = width * height * depth;
        var total;
        if(unidades > 0)
            total = (27+((vol * unidades)*0.00023979));
        else
           total = 0; 
        total = formatMoney(total, 2,'');
        $('#total'+id).val(total);
        
        calculaTotal();
    });
}

function formatMoney(number, places, symbol, thousand, decimal) {
    number = number || 0;
    places = !isNaN(places = Math.abs(places)) ? places : 2;
    symbol = symbol !== undefined ? symbol : "$";
    thousand = thousand || ",";
    decimal = decimal || ".";
    var negative = number < 0 ? "-" : "",
        i = parseInt(number = Math.abs(+number || 0).toFixed(places), 10) + "",
        j = (j = i.length) > 3 ? j % 3 : 0;
    return symbol + negative + (j ? i.substr(0, j) + thousand : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + thousand) + (places ? decimal + Math.abs(number - i).toFixed(places).slice(2) : "");
}


function calculaTotal()
{
    var sum = 0;
    var all = $('.totalBoxUnity').each(function(){
        sum += Number($(this).val());
    });
    $('#sumTotal').html(formatMoney(sum,2,'$'));
}
/**
 * Antes de hacer el sumbit debe verificar que se haya seleccionado fecha de recoleccion.
 */
function beforehSubmit()
{
    $('#submitButton').live('click',function(event){
        var total=$('#sumTotal').text().replace('$','');
        var replace = parseInt(total);
        
        if($('#boxSchedules').val()==0 || replace == 0 || $('#shippingDate').val()=='')
        {
            event.preventDefault();
            if($('#boxSchedules').val()==0)
                $('#shippingDateInformation').html('<div class="alert">Debe seleccionar una fecha de recoleccion</div>');
            else 
                if($('#shippingDate').val()=='')
                {
                    $('#shippingDateInformation').html('<div class="alert">No se puede generar el pedido, ya que no se ah calculado correctamente la hora de recoleccion y/o entrega</div>');
                }
                else
                {
                    $('#shippingDateInformation').html('<div class="alert">No se puede generar el pedido, ya que no se ah seleccionado ningun paquete');
                }
        }
    });
}
/**
 * Cambia el precio de los unitarios
 */
function changeUnitarys()
{
    var res=0;
    $('.prices').each(function (){
        res = (parseFloat($(this).attr('priceoriginal')) * sumFactors) + parseFloat($(this).attr('priceoriginal'));
        var resMoney = formatMoney(res, 2,'$ ');
        $(this).children().text(resMoney);
        $(this).children().next().val(res);
    });
    $('.boxunity').each(function(){
        res = (parseFloat($(this).attr('priceoriginal')) * sumFactors) + parseFloat($(this).attr('priceoriginal'));
        $(this).attr('price',res);
    });
    $('.boxunity').trigger('change', ['change', 'Event']);
}

function changePointOrigin()
{
    $('#pointSeller').change(function(){
       var originPoint = $(this).val();
        $.post(urlGetSchedules, {originPoint:originPoint,orderId:orderId}, function(data){
            $('#boxSchedules').html(data);
            $('#shippingDateInformation').html('<div class="alert">Seleccione la fecha de recolecci&oacute;n</div>');
        });
    });
}